const fs = require('fs-extra')
const uuidv1 = require('uuid/v1')
const config = require('../config/config')
const path = require('path')
const { Book } = require('../db')

function ensureFilePath (path) {
  const exists = fs.pathExistsSync(path)
  if (!exists) {
    fs.mkdirsSync(path)
  }
  return path
}

function uuid () {
  return uuidv1().replace(new RegExp('-', 'gm'), '')
}

async function task2Book (task, savePath) {
  const d = new Date()
  const distPath = path.join(
    config.getConf('book:persistence:savePath'),
    // Number.toString(d.getFullYear()), Number.toString(d.getMonth())
    `${d.getFullYear()}/${d.getMonth()}`
  )

  const filePath = path.join(ensureFilePath(distPath),
    uuid() + savePath.substring(savePath.lastIndexOf('.'))
  )

  const srcFile = fs.readFileSync(savePath)
  const size = srcFile.length
  // fs.copyFileSync(savePath, filePath)
  fs.writeFileSync(filePath, srcFile)

  const book = new Book({
    name: task.title,
    author: task.author,
    size,
    uri: filePath
  })
  await book.save()
}

function transferSrcBookToDist (srcPath) {
  const d = new Date()
  const distPath = path.join(
    config.getConf('book:persistence:savePath'),
    `${d.getFullYear()}/${d.getMonth()}`
  )

  const filePath = path.join(ensureFilePath(distPath),
    uuid() + srcPath.substring(srcPath.lastIndexOf('.'))
  )

  const srcFile = fs.readFileSync(srcPath)
  const size = srcFile.length
  fs.writeFileSync(filePath, srcFile)
  return {
    size,
    distPath: filePath
  }
}

module.exports = {
  ensureFilePath,
  task2Book,
  uuid,
  transferSrcBookToDist
}
